package com.qf.service.impl;

import com.qf.api.CacheFegin;
import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainService;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 限流策略
 */
@Service("limitFiveMinutes")
@Slf4j
public class LimitOneDayServiceImpl implements FilterChainService {

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Resource
    private CacheFegin cacheFegin;

    private final static Integer num=1;
    private final static long time=60;
    @Override
    public boolean strategy(StandardSubmit standardSubmit) throws Exception {
        log.info("开始执行限流策略");
        List<String> strings = cacheFegin.keysGet(CacheConstants.CACHE_PREFIX_SMS_LIMIT
                + standardSubmit.getClientID() + ":"
                + standardSubmit.getDestMobile());

        if (strings.size()>=num){
            log.error("达到上限");
            pushMsgUtil.sendLog(standardSubmit,StrategyConstants.STRATEGY_ERROR_LIMIT);
            pushMsgUtil.pushReport(standardSubmit,StrategyConstants.STRATEGY_ERROR_LIMIT);
            return false;
        }else {
            cacheFegin.limitSet(CacheConstants.CACHE_PREFIX_SMS_LIMIT
                                +standardSubmit.getClientID()+":"
                                +standardSubmit.getDestMobile()+":"+(new Date()),
                                String.valueOf(1),time);
            log.info("限流策略执行成功");
            return true;
        }

    }
}
